<template>
  <div>
    <el-affix :offset="50">
      <!--    可搜索的下拉框 -->
      <div class="h-full home-header">
        <el-select v-loading="schoolsLoading" class="home-select font-size-18"  v-model="currentSchoolId" :placeholder="$t('loc.centerOrSite')">
          <el-option v-for="item in schoolsIdName"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
        <div class="input-group right">
          <el-input v-if="false" size="small" v-model="searchContent" class="home-group-search"
                    placeholder="Search" :suffix-icon="Search"></el-input>
        </div>
      </div>
    </el-affix>
    <div class="home-container h-full" v-loading="groupsLoading">
        <div class="card-list">
          <el-card class="group-card" @click="cardClickHandler(group)" v-for="group in currentGroups">
            <el-dropdown trigger="click"
                         class="group-card-more-dropdown"
                         @command="command => handleGroupItemOperation(command, group)">
              <el-button @click.stop
                         class="group-card-more-button" type="text">
                <el-icon><MoreFilled /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit" style="color: #323338">
                    <el-icon class="m-r-xs"><EditPen /></el-icon>
                    <span>{{ $t('loc.edit') }}</span>
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided style="color: red;">
                    <el-icon class="m-r-xs">
                      <Delete />
                    </el-icon>
                    <span>{{ $t('loc.delete') }}</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>

            </el-dropdown>
            <img :src="getIconPath(group.iconPath)" style="width: 110px;height: 110px;">
            <div class="font-size-18 line-height-20 pointer add-margin-t-30">{{ group.name }}</div>
            <el-divider style="margin: 10px 0;border-top-color: #c8c8c8;"/>
            <div v-if="!group.isInactive" class="group-card-bottom">
              <div class="font-size-16 group-card-bottom-item" style="border-right: 1px solid #c8c8c8;" @click.stop="handleTeacherChild(group)">
                <div style="color: #23b7e5;display: block;">
                  {{ group.teacherCount }}
                </div>
                <div>{{ $t('loc.teacher') }}</div>
              </div>
              <div class="font-size-16 group-card-bottom-item" @click.stop="handleClickChild(group)">
                <div style="color: #23b7e5;display: block;">
                  {{ group.childCount }}
                </div>
                <div>{{ $t('loc.children') }}</div>
              </div>
              <div class="font-size-16 group-card-bottom-item" style="border-left: 1px solid #c8c8c8;" @click.stop="handleParentChild(group)">
                <div style="color: #23b7e5;display: block;">
                  {{ group.parentCount }} / {{ group.childCount }}
                </div>
                <div>{{ $t('loc.parent') }}</div>
              </div>
            </div>
            <div v-else class="group-card-bottom">
              <div class="font-size-16 group-card-bottom-item" @click.stop="handleClickChild(group)">
                <div style="color: #23b7e5;display: block;">
                  {{ group.childCount }}
                </div>
                <div>{{ $t('loc.children') }}</div>
              </div>
            </div>
          </el-card>
          <el-card class="group-card add-group-card" @click.stop="handleGroupItemOperation('add')">
            <el-icon class="font-size-40"><CirclePlus /></el-icon>
            <div>{{ $t('loc.addClass') }}</div>
          </el-card>
<!--        占位元素  -->
          <div></div>
          <div></div>
          <div></div>
        </div>
    </div>
    <GroupOperateDialog @needReLoadData="loadGroupList(currentSchoolId)" v-model:dialogVisible="dialogGroupVisible" :operateType="groupOperateType" :group="operatedGroup"></GroupOperateDialog>
    <ChildListDialog @needReLoadData="loadGroupList(currentSchoolId)" v-model:dialogVisible="dialogChildVisible" :group-id="operatedGroup.id"></ChildListDialog>
<!--    <ParentListDialog @needReLoadData="loadGroupList(currentSchoolId)" v-model:dialogVisible="dialogParentVisible" :group-id="operatedGroup.id"></ParentListDialog>-->
    <TeacherListDialog @needReLoadData="loadGroupList(currentSchoolId)" v-model:dialogVisible="dialogTeacherVisible" :group-id="operatedGroup.id"></TeacherListDialog>
    <invitationParentCodesDialog
        :group-id="operatedGroup.id"
        v-model:dialogVisible="dialogParentVisible"
    />
  </div>
</template>

<script>
import router from "@/router";
import {useStore} from "vuex";
import {Search, MoreFilled, Delete, EditPen, CirclePlus} from "@element-plus/icons-vue"
import SchoolApi from "@/api/school";
import GroupOperateDialog from "@/views/modules/home/GroupOperateDialog";
import ChildListDialog from "@/views/modules/home/child/ChildListDialog";
import ParentListDialog from "@/views/modules/home/parent/ParentListDialog";
import TeacherListDialog from "@/views/modules/home/TeacherListDialog";
import invitationParentCodesDialog from "@/views/modules/home/parent/invitationParentCodesDialog";
import GroupApi from "@/api/group";
import { ElNotification } from 'element-plus'
import {acrossRole} from "@/utils/common";

export default {
  name: 'HomeSite',
  components: {
    invitationParentCodesDialog,
    TeacherListDialog,
    ParentListDialog,
    ChildListDialog,
    GroupOperateDialog,
    Search,
    MoreFilled,
    EditPen,
    Delete,
    CirclePlus
  },
  // 设置 data
  data: function () {
    return {
      Search: Search,
      searchContent: '',
      currentSchoolId: '',
      currentGroups: [],
      schoolsIdName: [],
      schoolsLoading: false,
      groupsLoading: false,
      dialogGroupVisible: false,
      groupOperateType: '', // adminEdit edit add
      operatedGroup: {},
      dialogChildVisible: false,
      dialogParentVisible: false,
      dialogTeacherVisible: false,
      visibleInviteParentsDialog: false,
    }
  },
  created() {
    this.init()
  },
  computed: {
    currentUser () {
      return useStore().state.user.currentUser
    },
  },
  watch: {
    currentSchoolId: {
      immediate: true,
      handler: function (val, oldVal) {
        if (val && val !== oldVal) {
          router.push({name: `schools`, params: {schoolId: val}})
        }
      },
    },
    // 监听路由
    $route: {
      immediate: true,
      handler: function (to, oldVal) {
        if (to.params.schoolId) {
          if (!oldVal || !oldVal.params || this.currentSchoolId !== oldVal.params.schoolId ) {
            this.currentSchoolId = to.params.schoolId
            this.loadGroupList(this.currentSchoolId)
          }
        }
      },
    },
  },
  methods: {
    init() {
      if (acrossRole('PARENT')) {
        router.push({name: 'parent'})
      } else {
        this.loadSchoolList()
      }
    },
    handleGroupItemOperation (command, item) {
      console.log('handleClickViewTabItemOperation',command, item)
      if (command === 'edit') {
        this.groupOperateType = 'edit'
        this.operatedGroup = item
        this.dialogGroupVisible = true
      }
      if (command === 'delete') {
        this.deleteHandler(item)
      }
      if (command === 'add') {
        this.groupOperateType = 'add'
        this.operatedGroup = {schoolId: this.currentSchoolId}
        this.dialogGroupVisible = true
      }
    },
    // 删除班级
    deleteHandler(group) {
      if (!group || !group.id) {
        return
      }
      this.$confirm(this.$t('loc.cfmAgn'), this.$t('loc.tip'), {
        confirmButtonText: this.$t('loc.done'),
        cancelButtonText: this.$t('loc.cancel'),
        type: 'warning',
      }).then(() => {
        GroupApi.deleteGroup(group.id).then(res => {
          ElNotification({
            title: this.$t('loc.tip'),
            message: this.$t('loc.gpDelSfy'),
            position: 'bottom-right',
          })
          this.loadGroupList(this.currentSchoolId)
        }).catch(error => {
          console.log('error', error)
          this.$message.error(error.response.data.description)
        });

      }).catch(() => {
        this.$message.error(error.response.data.description)
      });
    },
    loadSchoolList () {
      this.schoolsLoading = true
      SchoolApi.getSchoolsIdNameByUserId(this.currentUser.userId).then(res => {
        this.schoolsLoading = false
        let schoolsIdName = res.schoolsIdName
        if (!schoolsIdName || schoolsIdName.length === 0) {
          this.$message.error('您还没有加入任何幼儿园')
          return
        }
        this.schoolsIdName = schoolsIdName
        // 將  schoolsIdName的 id 屬性抽取出来成为一个新的数组
        let schoolIds = schoolsIdName.map(item => item.id)
        if (!this.currentSchoolId) {
          this.currentSchoolId = schoolIds[0]
        }
        // 刷新組件
      }).catch(error => {
        this.schoolsLoading = false
        this.$message.error(error)
      })
    },
    loadGroupList (schoolId) {
      this.groupsLoading = true
      SchoolApi.getSchoolAndGroupInfo(schoolId).then(res => {
        // 將 离校的班级放到最后 isInactive: true
        let groups = res.groups.filter(item => !item.isInactive)
        groups = groups.concat(res.groups.filter(item => item.isInactive))
        this.currentGroups = groups
        this.groupsLoading = false
      }).catch(error => {
        this.groupsLoading = false
        this.$message.error(error)
        this.$message.error(error.response.data.description)
      })
    },
    handleTeacherChild (group) {
      this.operatedGroup = group
      this.dialogTeacherVisible = true
    },
    handleParentChild (group) {
      this.operatedGroup = group
      this.dialogParentVisible = true
    },
    handleClickChild (group) {
      this.operatedGroup = group
      this.dialogChildVisible = true
    },
    getIconPath(iconPath) {
      if (!iconPath) {
        iconPath = 1
      }
      return require(`@/assets/img/group/${iconPath}.png`)
    },
    cardClickHandler (group) {
      if (group.childCount === 0) {
        this.$message.error(this.$t('loc.addChildToClass'))
        return
      }
      router.push({name: 'note', params: {
        schoolId: group.schoolId,
        groupId: group.id}}
      )
    },
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
.home-header {
  width: 100%;
  background-color: #e4eaec;
  height: 50px;
  position:relative;
  text-align: center;
  .input-group {
    position: absolute;
    top: 5px;
    right: 5px;
  }
}

.home-select {
  height: 100%;

  /deep/ .select-trigger {
    height: 100%;
  }

  /deep/ .el-input {
    height: 100%;
  }

  /deep/ .el-input__wrapper {
    background-color: #e4eaec;
  }

  /deep/ .el-input__inner {
    text-align: center;
    font-size: 20px;
    color: #58666e;
  }
  /deep/ .el-select-dropdown__wrap {
    max-height: 300px !important;
    overflow-y: auto !important;
  }

}


.home-group-search {
  width: 240px;
  height: 40px;

  /deep/ .el-input__wrapper {
    border-radius: 20px;
  }
}

.card-list {
  margin-top: 20px;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}

.home-container{
  margin: 0 auto;
}
@media (min-width: 576px){
  .home-container {
    width: 540px;
  }
}
@media (min-width: 992px){
  .home-container {
    width: 870px;
  }
}
@media (min-width: 1200px) {
  .home-container {
    width: 970px;
  }

}
@media (min-width: 1300px){
  .home-container {
    width: 1050px;
  }
}
@media (min-width: 1500px){
  .home-container {
    width: 1100px;
  }
}

.group-card {
  position: relative;
  max-width: 260px;
  margin: 12px;
  height: fit-content;
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  -webkit-transition: border .2s ease-in-out;
  -o-transition: border .2s ease-in-out;
  transition: border .2s ease-in-out;
  cursor: pointer;
  .group-card-more-dropdown {
    position: absolute;
    top: 0;
    right: 7px;
  }
  .group-card-more-button {
    cursor: pointer;
    color: #333;
    height: 25px;
    width: 30px;
  }
  .group-card-more-button:hover {
    color: #10B3B7;
    background-color: #e4eaec;
  }
  /deep/ .el-card__body {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 25px var(--el-card-padding);
  }

  .group-card-bottom {
    display: flex;
    color: rgb(51, 51, 51);
    width: 100%;
    justify-content: space-around;
  }

  .group-card-bottom-item {
    cursor: pointer;
    width: 30%;
    text-align: center;
  }
}

.group-card:hover {
  border: 1px solid #10B3B7;
}
.add-group-card:hover {
  color: #10B3B7;
  border: 3px dashed #10B3B7;
}
.add-group-card {
  border: 3px dashed #ddd;
  padding-top: 88px;
  padding-bottom: 77px;
  cursor: pointer;
  color: #ddd;
}
</style>
